<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>springboot读取yml配置文件的几种方式 | 牛牛&amp;blog</title><meta name="author" content="牛牛"><meta name="copyright" content="牛牛"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="1、springboot读取yml配置文件的几种方式:一、yml文件YAML语法基本介绍1、以缩进代表层级关系2、缩进不能使用tab，只能用空格3、空格个数不重要，但是同一层级必须左对齐4、大小写敏感5、数据格式为，名称:(空格)值6、注释单行用#，只能注释单行    各类数据书写形式：1、数字，字符串，布尔等# key: value形式name: zsage: 20enable: true  2">
<meta property="og:type" content="article">
<meta property="og:title" content="springboot读取yml配置文件的几种方式">
<meta property="og:url" content="https://code-ran.gitee.io/2022/11/23/springboot%E8%AF%BB%E5%8F%96yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/index.html">
<meta property="og:site_name" content="牛牛&amp;blog">
<meta property="og:description" content="1、springboot读取yml配置文件的几种方式:一、yml文件YAML语法基本介绍1、以缩进代表层级关系2、缩进不能使用tab，只能用空格3、空格个数不重要，但是同一层级必须左对齐4、大小写敏感5、数据格式为，名称:(空格)值6、注释单行用#，只能注释单行    各类数据书写形式：1、数字，字符串，布尔等# key: value形式name: zsage: 20enable: true  2">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-11-23T07:28:14.000Z">
<meta property="article:modified_time" content="2023-11-02T03:32:07.206Z">
<meta property="article:author" content="牛牛">
<meta property="article:tag" content="springboot">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/img/myfavicon.png"><link rel="canonical" href="https://code-ran.gitee.io/2022/11/23/springboot%E8%AF%BB%E5%8F%96yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'springboot读取yml配置文件的几种方式',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-02 11:32:07'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/style.css"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/ys.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">26</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">牛牛&amp;blog</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">springboot读取yml配置文件的几种方式</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-23T07:28:14.000Z" title="发表于 2022-11-23 15:28:14">2022-11-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-02T03:32:07.206Z" title="更新于 2023-11-02 11:32:07">2023-11-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/springboot%E7%9B%B8%E5%85%B3/">springboot相关</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="springboot读取yml配置文件的几种方式"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h4 id="1、springboot读取yml配置文件的几种方式"><a href="#1、springboot读取yml配置文件的几种方式" class="headerlink" title="1、springboot读取yml配置文件的几种方式:"></a>1、springboot读取yml配置文件的几种方式:</h4><h5 id="一、yml文件YAML语法基本介绍"><a href="#一、yml文件YAML语法基本介绍" class="headerlink" title="一、yml文件YAML语法基本介绍"></a>一、yml文件YAML语法基本介绍</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">1、以缩进代表层级关系</span><br><span class="line">2、缩进不能使用tab，只能用空格</span><br><span class="line">3、空格个数不重要，但是同一层级必须左对齐</span><br><span class="line">4、大小写敏感</span><br><span class="line">5、数据格式为，名称:(空格)值</span><br><span class="line">6、注释单行用#，只能注释单行</span><br></pre></td></tr></table></figure>



<h5 id="各类数据书写形式："><a href="#各类数据书写形式：" class="headerlink" title="各类数据书写形式："></a>各类数据书写形式：</h5><h6 id="1、数字，字符串，布尔等"><a href="#1、数字，字符串，布尔等" class="headerlink" title="1、数字，字符串，布尔等"></a>1、数字，字符串，布尔等</h6><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="comment"># key: value形式</span></span><br><span class="line"><span class="attr">name:</span> <span class="string">zs</span></span><br><span class="line"><span class="attr">age:</span> <span class="number">20</span></span><br><span class="line"><span class="attr">enable:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<h6 id="2、数组，集合（List，Set）"><a href="#2、数组，集合（List，Set）" class="headerlink" title="2、数组，集合（List，Set）"></a>2、数组，集合（List，Set）</h6><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 方式一：换行缩进，使用-表示一个元素（常用）</span></span><br><span class="line"><span class="comment"># 如Java bean中的List&lt;String&gt; tels 或者 String[] tels</span></span><br><span class="line"><span class="attr">tels:</span> </span><br><span class="line">  <span class="bullet">-</span> <span class="number">110</span></span><br><span class="line">  <span class="bullet">-</span> <span class="number">120</span></span><br><span class="line"><span class="comment"># List&lt;Users&gt; users</span></span><br><span class="line"><span class="attr">users:</span> </span><br><span class="line">  <span class="bullet">-</span> <span class="attr">name:</span> <span class="string">zs</span></span><br><span class="line">    <span class="attr">age:</span> <span class="number">20</span></span><br><span class="line">  <span class="bullet">-</span> <span class="attr">name:</span> <span class="string">ls</span></span><br><span class="line">    <span class="attr">age:</span> <span class="number">30</span></span><br><span class="line"><span class="comment"># 方式二：单行配置</span></span><br><span class="line"><span class="attr">tels:</span> <span class="number">110</span><span class="string">,</span> <span class="number">120</span></span><br><span class="line"><span class="attr">users:</span> &#123;<span class="attr">name:</span> <span class="string">zs</span>, <span class="attr">age:</span> <span class="number">20</span>&#125;<span class="string">,</span> &#123;<span class="attr">name:</span> <span class="string">ls</span>, <span class="attr">age:</span> <span class="number">30</span>&#125;</span><br></pre></td></tr></table></figure>

<h6 id="3、Map和对象"><a href="#3、Map和对象" class="headerlink" title="3、Map和对象"></a>3、Map和对象</h6><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 方式一：多行配置</span></span><br><span class="line"><span class="comment"># 如Map&lt;String, Integer&gt; score或者Score score</span></span><br><span class="line"><span class="attr">score:</span></span><br><span class="line">  <span class="attr">chinese:</span> <span class="number">95</span></span><br><span class="line">  <span class="attr">english:</span> <span class="number">90</span></span><br><span class="line"><span class="comment"># 方式二：单行配置</span></span><br><span class="line"><span class="attr">score:</span> &#123;<span class="attr">chinese:</span> <span class="number">95</span>, <span class="attr">english:</span> <span class="number">90</span>&#125;</span><br></pre></td></tr></table></figure>



<h5 id="二、读取yml文件："><a href="#二、读取yml文件：" class="headerlink" title="二、读取yml文件："></a>二、读取yml文件：</h5><p>先在application.yml中写好相关配置：</p>
<figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="attr">user:</span></span><br><span class="line">  <span class="attr">user-name:</span> <span class="string">Mr.Zhang</span></span><br><span class="line">  <span class="attr">age:</span> <span class="number">38</span></span><br><span class="line">  <span class="attr">tels:</span></span><br><span class="line">    <span class="bullet">-</span> <span class="number">110</span></span><br><span class="line">    <span class="bullet">-</span> <span class="number">120</span></span><br><span class="line">  <span class="attr">score:</span></span><br><span class="line">    <span class="attr">chinese:</span> <span class="number">95</span></span><br><span class="line">    <span class="attr">english:</span> <span class="number">90</span></span><br><span class="line">  <span class="attr">users:</span></span><br><span class="line">    <span class="bullet">-</span> <span class="attr">user-name:</span> <span class="string">zs</span></span><br><span class="line">      <span class="attr">age:</span> <span class="number">5</span></span><br><span class="line">    <span class="bullet">-</span> <span class="attr">user-name:</span> <span class="string">ls</span></span><br><span class="line">      <span class="attr">age:</span> <span class="number">12</span></span><br></pre></td></tr></table></figure>

<h6 id="方式一：-Value注解（值绑定）"><a href="#方式一：-Value注解（值绑定）" class="headerlink" title="方式一： @Value注解（值绑定）"></a>方式一： @Value注解（值绑定）</h6><p>定义一个JavaBean，提供get和set方法（必须），用于接收从yml读取的数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Users</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@Value</span> 值绑定</span></span><br><span class="line"><span class="comment">     * 在每个对应的属性上加<span class="doctag">@Value</span>注解，注解中的内容填写yml中对应的属性，</span></span><br><span class="line"><span class="comment">     * 使用<span class="doctag">@Value</span>注解时，yml中的属性名和JavaBean中的属性名可以不对应，但是数据类型需要对应</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;user.userName&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;user.age&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;user.tesl&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String[] tels;</span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;user.score&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, Integer&gt; score;</span><br><span class="line">    <span class="meta">@Value(&quot;$&#123;user.users&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;Users&gt; children;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h6 id="方式二：-ConfigurationProperties注解（松散绑定）"><a href="#方式二：-ConfigurationProperties注解（松散绑定）" class="headerlink" title="方式二： @ConfigurationProperties注解（松散绑定）"></a>方式二： @ConfigurationProperties注解（松散绑定）</h6><p>定义一个JavaBean，提供get和set方法，用于接收从yml读取的数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ConfigurationProperties 松散绑定，只需要通过prefix属性指定属性参数名的前缀即可</span></span><br><span class="line"><span class="comment"> * 松散绑定的bean属性名需要跟yml中的属性名对应，但是不需要精确匹配，</span></span><br><span class="line"><span class="comment"> * yml可依据约定使用驼峰（如：userName）、&quot;-&quot;线（如：user-name）、全大写加上&quot;_&quot;（如：USER_NAME）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@ConfigurationProperties(prefix = &quot;user&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Users</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String userName;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line">    <span class="keyword">private</span> String[] tels;</span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, Integer&gt; score;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Teacher&gt; oldTeachers;</span><br><span class="line">    <span class="keyword">private</span> List&lt;Teacher&gt; newTeachers;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="单元测试："><a href="#单元测试：" class="headerlink" title="单元测试："></a>单元测试：</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在单元测试中注入这个bean</span></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> Users user;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">testUsers</span><span class="params">()</span></span>&#123;</span><br><span class="line">    System.out.println(user.getName());</span><br><span class="line">    System.out.println(user.getAge());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Mr.Zhang</span><br><span class="line">38</span><br></pre></td></tr></table></figure>

<h6 id="方式三：-YamlMapFactoryBean"><a href="#方式三：-YamlMapFactoryBean" class="headerlink" title="方式三： YamlMapFactoryBean"></a>方式三： YamlMapFactoryBean</h6><p>通过这个factoryBean可以直接返回一个Map，而不需要使用JavaBean去接收yml读取的值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] arg0)</span></span>&#123;</span><br><span class="line">    YamlMapFactoryBean yamlMapFactoryBean = <span class="keyword">new</span> YamlMapFactoryBean();</span><br><span class="line">    <span class="comment">//可以加载多个yml文件</span></span><br><span class="line">    yamlMapFactoryBean.setResources(<span class="keyword">new</span> ClassPathResource(<span class="string">&quot;application.yml&quot;</span>));</span><br><span class="line">    <span class="comment">//通过getObject()方法获取Map对象</span></span><br><span class="line">    Map&lt;String, Object&gt; map = yamlMapFactoryBean.getObject();</span><br><span class="line">    System.out.println(map);</span><br><span class="line">    map.keySet().forEach(item -&gt; &#123;</span><br><span class="line">        <span class="comment">//可以将map中的值强转为LinkedHashMap对象</span></span><br><span class="line">        LinkedHashMap&lt;String, Object&gt; linkedHashMap = (LinkedHashMap&lt;String, Object&gt;) (map.get(item));</span><br><span class="line">        System.out.println(linkedHashMap.get(<span class="string">&quot;tels&quot;</span>));</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&#123;user=&#123;user-name=zhangsan, age=18, tels=[13479990123, 13567890987, null], score=&#123;chinese=95, english=90&#125;, users=[&#123;name=Mr.Zhang, age=29&#125;, &#123;name=Mr.Li, age=39&#125;]&#125;&#125;</span><br><span class="line">[13479990123, 13567890987]</span><br></pre></td></tr></table></figure>

<h6 id="方式四：YamlPropertiesFactoryBean"><a href="#方式四：YamlPropertiesFactoryBean" class="headerlink" title="方式四：YamlPropertiesFactoryBean"></a>方式四：YamlPropertiesFactoryBean</h6><p>通过这个类可以直接返回Properties对象</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] arg0)</span></span>&#123;</span><br><span class="line">    YamlPropertiesFactoryBean factoryBean = <span class="keyword">new</span> YamlPropertiesFactoryBean();</span><br><span class="line">    factoryBean.setResources(<span class="keyword">new</span> ClassPathResource(<span class="string">&quot;application.yml&quot;</span>));</span><br><span class="line">    Properties properties = factoryBean.getObject();</span><br><span class="line">    properties.keySet().forEach(key -&gt; System.out.println(key + <span class="string">&quot;=====&quot;</span> + properties.get(key)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">user.age=====18</span><br><span class="line">user.users[0].age=====5</span><br><span class="line">user.users[0].user-name=====zs</span><br><span class="line">user.users[1].age=====15</span><br><span class="line">user.users[1].user-name=====ls</span><br><span class="line">user.score.chinese=====95</span><br><span class="line">user.score.english=====90</span><br><span class="line">user.tels[0]=====13479990123</span><br><span class="line">user.tels[1]=====13567890987</span><br><span class="line">user.user-name=====zhangsan</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://code-ran.gitee.io">牛牛</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://code-ran.gitee.io/2022/11/23/springboot%E8%AF%BB%E5%8F%96yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/">https://code-ran.gitee.io/2022/11/23/springboot%E8%AF%BB%E5%8F%96yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://code-ran.gitee.io" target="_blank">牛牛&blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/springboot/">springboot</a></div><div class="post_share"><div class="social-share" data-image="" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/11/23/mybatis%E5%85%A8%E5%8A%A8%E6%80%81%E6%8F%92%E5%85%A5/"><img class="prev-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">MyBatis全动态插入</div></div></a></div><div class="next-post pull-right"><a href="/2022/11/23/springboot%E8%AF%BB%E5%8F%96%E9%A1%B9%E7%9B%AE%E4%B8%8B%E7%9A%84%E6%96%87%E4%BB%B6/"><img class="next-cover" src="" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">springboot读取项目下的文件</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2024/04/30/CommandLineRunner%E5%92%8CApplicationRunner%E7%94%A8%E6%B3%95%E4%B8%8E%E5%8C%BA%E5%88%AB/" title="CommandLineRunner和ApplicationRunner用法与区别"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-30</div><div class="title">CommandLineRunner和ApplicationRunner用法与区别</div></div></a></div><div><a href="/2024/04/30/springboot%E6%B3%A8%E8%A7%A3%E7%9B%B8%E5%85%B3/" title="springboot注解相关"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2024-04-30</div><div class="title">springboot注解相关</div></div></a></div><div><a href="/2022/11/23/springboot%E8%AF%BB%E5%8F%96%E9%A1%B9%E7%9B%AE%E4%B8%8B%E7%9A%84%E6%96%87%E4%BB%B6/" title="springboot读取项目下的文件"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-11-23</div><div class="title">springboot读取项目下的文件</div></div></a></div><div><a href="/2023/11/17/springboot%E6%8B%A6%E6%88%AA%E5%99%A8/" title="springboot拦截器"><img class="cover" src="" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-11-17</div><div class="title">springboot拦截器</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/ys.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">牛牛</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">52</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">26</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/code-ran"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">本blog内容仅用于个人学习使用!</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#1%E3%80%81springboot%E8%AF%BB%E5%8F%96yml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="toc-number">1.</span> <span class="toc-text">1、springboot读取yml配置文件的几种方式:</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B8%80%E3%80%81yml%E6%96%87%E4%BB%B6YAML%E8%AF%AD%E6%B3%95%E5%9F%BA%E6%9C%AC%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.1.</span> <span class="toc-text">一、yml文件YAML语法基本介绍</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%90%84%E7%B1%BB%E6%95%B0%E6%8D%AE%E4%B9%A6%E5%86%99%E5%BD%A2%E5%BC%8F%EF%BC%9A"><span class="toc-number">1.2.</span> <span class="toc-text">各类数据书写形式：</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#1%E3%80%81%E6%95%B0%E5%AD%97%EF%BC%8C%E5%AD%97%E7%AC%A6%E4%B8%B2%EF%BC%8C%E5%B8%83%E5%B0%94%E7%AD%89"><span class="toc-number">1.2.1.</span> <span class="toc-text">1、数字，字符串，布尔等</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#2%E3%80%81%E6%95%B0%E7%BB%84%EF%BC%8C%E9%9B%86%E5%90%88%EF%BC%88List%EF%BC%8CSet%EF%BC%89"><span class="toc-number">1.2.2.</span> <span class="toc-text">2、数组，集合（List，Set）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#3%E3%80%81Map%E5%92%8C%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.2.3.</span> <span class="toc-text">3、Map和对象</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E8%AF%BB%E5%8F%96yml%E6%96%87%E4%BB%B6%EF%BC%9A"><span class="toc-number">1.3.</span> <span class="toc-text">二、读取yml文件：</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A-Value%E6%B3%A8%E8%A7%A3%EF%BC%88%E5%80%BC%E7%BB%91%E5%AE%9A%EF%BC%89"><span class="toc-number">1.3.1.</span> <span class="toc-text">方式一： @Value注解（值绑定）</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A-ConfigurationProperties%E6%B3%A8%E8%A7%A3%EF%BC%88%E6%9D%BE%E6%95%A3%E7%BB%91%E5%AE%9A%EF%BC%89"><span class="toc-number">1.3.2.</span> <span class="toc-text">方式二： @ConfigurationProperties注解（松散绑定）</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95%EF%BC%9A"><span class="toc-number">2.</span> <span class="toc-text">单元测试：</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%89%EF%BC%9A-YamlMapFactoryBean"><span class="toc-number">2.0.1.</span> <span class="toc-text">方式三： YamlMapFactoryBean</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E5%9B%9B%EF%BC%9AYamlPropertiesFactoryBean"><span class="toc-number">2.0.2.</span> <span class="toc-text">方式四：YamlPropertiesFactoryBean</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/04/30/springboot%E6%B3%A8%E8%A7%A3%E7%9B%B8%E5%85%B3/" title="springboot注解相关">springboot注解相关</a><time datetime="2024-04-30T03:20:37.000Z" title="发表于 2024-04-30 11:20:37">2024-04-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/04/30/CommandLineRunner%E5%92%8CApplicationRunner%E7%94%A8%E6%B3%95%E4%B8%8E%E5%8C%BA%E5%88%AB/" title="CommandLineRunner和ApplicationRunner用法与区别">CommandLineRunner和ApplicationRunner用法与区别</a><time datetime="2024-04-30T02:42:21.000Z" title="发表于 2024-04-30 10:42:21">2024-04-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/08/%E5%A5%BD%E6%96%87%E6%94%B6%E8%97%8F/" title="好文收藏">好文收藏</a><time datetime="2023-12-08T08:40:13.000Z" title="发表于 2023-12-08 16:40:13">2023-12-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/08/springboot%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8B%E8%BD%BD/" title="springboot文件上传下载">springboot文件上传下载</a><time datetime="2023-12-08T03:30:54.000Z" title="发表于 2023-12-08 11:30:54">2023-12-08</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/12/05/linux%E4%BD%BF%E7%94%A8curl%E5%91%BD%E4%BB%A4%E5%8F%91%E9%80%81%E8%AF%B7%E6%B1%82/" title="linux使用curl命令发送请求">linux使用curl命令发送请求</a><time datetime="2023-12-05T05:56:19.000Z" title="发表于 2023-12-05 13:56:19">2023-12-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2024 By 牛牛</div><div class="footer_custom_text">Hi, Welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>